package com.wyz.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wyz.mapper.SupplierMapper;
import com.wyz.model.Supplier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author wk
 * @desc
 * @date 2024/7/26 8:51
 */
@Controller
public class SupplierController {
    @Resource
    private SupplierMapper supplierMapper;
    @RequestMapping("/supplier/getAllSupplier")
    public String getAllSupplier(HttpSession session) {
        List<Supplier> suppliers = supplierMapper.selectList(null);
        System.out.println(suppliers);
        session.setAttribute("suppliers",suppliers);
        return "back/supplier";
    }
    @RequestMapping("/supplier/addSupplier")
    public String supplierAdd() {
        return "back/addsupplier";
    }
    @RequestMapping("/supplier/add.do")
    public String supplierAdd(Supplier supplier,HttpSession session) {
        supplierMapper.insert(supplier);
        return "redirect:/supplier/getAllSupplier";
    }
    @RequestMapping("supplier/getSupplierById")
    public String getSupplierById(Integer id,HttpSession session) {
        Supplier supplier = supplierMapper.selectById(id);
        session.setAttribute("supplier",supplier);
        return "back/supplierView";
    }
    @RequestMapping("/supplier/deleteSupplier")
    public String supplierDel(Integer id) {
        supplierMapper.deleteById(id);
        return "redirect:/supplier/getAllSupplier";
    }
    @RequestMapping("/supplier/edit.do")
    public String supplierEdit(Integer id,HttpSession session) {
        Supplier supplier = supplierMapper.selectById(id);
        session.setAttribute("supplier",supplier);
        return "back/editsupplier";
    }
    @RequestMapping("/supplier/editHandler.do")
    public String supplierEditHandler(Supplier supplier,HttpSession session) {
        int result =supplierMapper.updateById(supplier);
        if (result == 0) {
            session.setAttribute("error", "修改失败"); // 修改失败后将错误信息存入session中
            return "back/editsupplier";
        } else {
            session.removeAttribute("error"); // 修改成功后清除session中错误信息
            return "redirect:/supplier/getAllSupplier"; // 修改成功后重定向跳转到登录页面
        }
    }
    //进行多条件的模糊查询并排序
    @RequestMapping("/supplier/search.do")
    public String search(String condition,String sort,HttpSession session) {
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("supplierCompany","%"+condition+"%").or().like("functionaryName","%"+condition+"%").orderByAsc(sort);
        List<Supplier> suppliers = supplierMapper.selectList(queryWrapper);
        session.setAttribute("suppliers",suppliers);
        return "back/supplier";
    }

}
